/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;
using MyPhotoIndex.Utilities;

namespace MyPhotoIndex
{
    class FileDragDrop : IMessageFilter , IDisposable
    {
        IntPtr m_hwnd;

        public event EventHandler<FileDropEventArgs> FileDroppedEvent;

        public FileDragDrop(Form form)
		{
            m_hwnd = form.Handle;

			Application.AddMessageFilter(this);
            Win32Interop.DragAcceptFiles(m_hwnd, true);
		}

		public bool PreFilterMessage(ref Message m)
		{
            if (m.Msg == Win32Interop.WM_DROPFILES)
			{
                List<String> files = new List<string>();
                int nfiles = Win32Interop.DragQueryFile(m.WParam, -1, null, 0);
                for (int ii = 0; ii < nfiles; ii++)
                {
                    StringBuilder sb = new StringBuilder(256);
                    Win32Interop.DragQueryFile(m.WParam, ii, sb, 256);
                    files.Add(sb.ToString());
                }

                ThreadPool.QueueUserWorkItem(new WaitCallback(HandleDroppedFiles), files);
            //    HandleDroppedFiles(files);

                Win32Interop.DragFinish(m.WParam);
				return true;
			}

			return false;
		}

		public void Dispose()
		{
            Win32Interop.DragAcceptFiles(m_hwnd, false);
			Application.RemoveMessageFilter(this);
		}

        public void HandleDroppedFiles(Object state)
		{
            List<String> files = state as List<String>;

            if (FileDroppedEvent != null)
            {
                FileDroppedEvent.Invoke(this, new FileDropEventArgs(files));
            }
		}
	}
}